package com.study.book.utils;

import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Slf4j
public class RandomUtil {
    /**
     * java生成随机数字和字母组合10位数
     *
     * @param length[生成随机数的长度]
     * @return
     */
    public static String getRandomNickname(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {

            val += String.valueOf(random.nextInt(10));

        }
        return val;
    }

    //生成随机用户名，数字和字母组成,
    public static String getStringRandom(int length) {

        String val = "";
        Random random = new Random();

        //参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    private static String lastResetDate = null;

    private static int userIdCounter = 1;

    /**
     * 生成订单号（25位）：时间（精确到毫秒）+3位随机数+5位用户id
     */
    public static synchronized String getOrderNum(Integer userId) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd"); // 日期格式
        String currentDate = dateFormat.format(new Date()); // 当前日期部分
        if (!currentDate.equals(lastResetDate)) {
            lastResetDate = currentDate;
            userIdCounter = 1; // 重置用户ID计数器为1
        }else {
            userIdCounter++;
        }
        String userIdPart = String.format("%03d", userId);
        String random = String.format("%03d", userIdCounter);
        String orderNum=currentDate+random+userIdPart;
        return orderNum;
    }

}
